package com.wwwarehouse.contract.orders.place_order;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.SpaceItemDecoration;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.contract.adapter.PlaceOrdersBrowseGoodsDetailsRecycleAdapter;
import com.wwwarehouse.contract.bean.PlaceOrdersAddShoppingCartBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseConfirmBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseEvent;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseGoodsBean;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.orders.BuyerAnimatorUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;


/**
 * 下单->浏览商品Details
 * Created by ShineF on 2017/10/18 0018.
 */

public class PlaceOrdersBrowseGoodsDetailsFragment extends BaseFragment implements PlaceOrdersBrowseGoodsDetailsRecycleAdapter.OnItemClickListener, PlaceOrdersBrowseGoodsDetailsRecycleAdapter.OnAddGoodsListener {

    private RecyclerView mRvContent;
    private boolean isMeasured = false;
    private PlaceOrdersBrowseGoodsDetailsRecycleAdapter mAdapter;
    private ArrayList<PlaceOrdersBrowseGoodsBean.ItemListBean> mBeanList;
    private RelativeLayout mParentItem;
    private Button mConfirmBtn;
    private View mShoppintView;
    private int mShoppingNum = -1;
    private static final int LOAD_BROWSE_DATA = 1;
    private static final int ADD_SHOPPINT_CART = 2;
    private String mDemandId;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_place_orders_brower_goods_details, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRvContent = $(R.id.rv_content);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof PlaceOrdersBrowseGoodsDetailsFragment) {
            mActivity.setTitle(getString(R.string.browse_product));
        }
    }

    @Override
    public void requestDatas() {

    }


    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        initData();
        return null;
    }

    public void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mRvContent.addItemDecoration(new SpaceItemDecoration(0, 0));
        mRvContent.setLayoutManager(new GridLayoutManager(mActivity, 1));
        ArrayList<String> mFilterList;
        Bundle bundle = getArguments();
        if (null != bundle) {
            mFilterList = bundle.getStringArrayList("filtName");
            mDemandId = bundle.getString("demandId");
            String mSearchText = bundle.getString("searchName");
            String mSortText = bundle.getString("sortName");
            mShoppingNum = bundle.getInt("shoppingNum");
            mBeanList = bundle.getParcelableArrayList("dataList");
            EventBus.getDefault().post(new PlaceOrdersBrowseEvent("gotoOrders", mShoppingNum));
            int page = bundle.getInt("page");
            if (mBeanList != null && page == 1) {
                ViewTreeObserver observer = mRvContent.getViewTreeObserver();
                observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    public boolean onPreDraw() {
                        if (!isMeasured) {
                            setHeight(mRvContent.getMeasuredHeight());
                        }
                        return true;
                    }
                });
            } else {
                requestHttp(page, mSearchText, mSortText, mFilterList);
            }
        }
    }

    public void requestHttp(int page, String mSearchText, String mSortText, ArrayList mFilterList) {
        Map<String, Object> map = new HashMap<>();
//        map.put("demandId", "10001589");
        map.put("demandId", mDemandId);
        map.put("page", page);
        map.put("search", mSearchText);
        map.put("size", "5");
        map.put("sort", mSortText);
        map.put("supplierType", mFilterList);
        loadData(ContractConstant.PLACE_ORDERS_BROWSE_GOODS, map, LOAD_BROWSE_DATA);
    }

    public void loadData(String url, Map<String, Object> map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int i) {
                if (i == LOAD_BROWSE_DATA) {
                    if (commonClass.getCode().equals("0")) {
                        PlaceOrdersBrowseGoodsBean bean =
                                JSON.parseObject(commonClass.getData().toString(), PlaceOrdersBrowseGoodsBean.class);
                        if (bean != null) {
                            setData(bean);
                        }
                    }

                } else if (i == ADD_SHOPPINT_CART) {
                    if (commonClass.getCode().equals("0")) {
                        PlaceOrdersAddShoppingCartBean addBean =
                                JSON.parseObject(commonClass.getData().toString(), PlaceOrdersAddShoppingCartBean.class);
                        if (mParentItem != null && mConfirmBtn != null)
                            BuyerAnimatorUtils.addCart(mActivity, mParentItem, mShoppintView, mConfirmBtn);
//                        ToastUtils.showToast(getString(R.string.add_success));
                        mShoppingNum = addBean.getItemCount();
                        EventBus.getDefault().post(new PlaceOrdersBrowseEvent("gotoOrders", mShoppingNum));
                    } else if (commonClass.getCode().equals("704002")) { //商品已被下架
                        ToastUtils.showToast(commonClass.getMsg());
                    } else if (commonClass.getCode().equals("704001")) { //当前商品库存不足
                        ToastUtils.showToast(commonClass.getMsg());
                    } else if (commonClass.getCode().equals("70301")) { //购物车商品已经存在
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                }
            }

            @Override
            public void onFailed(String s, int i) {

            }

            @Override
            public void onFinish(int i) {

            }
        }, what);
    }

    private void setData(PlaceOrdersBrowseGoodsBean bean) {
        mBeanList = bean.getItemList();
        mShoppingNum = bean.getItemCount();
        ViewTreeObserver observer = mRvContent.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (!isMeasured) {
                    setHeight(mRvContent.getMeasuredHeight());
                }
                return true;
            }
        });
    }


    public void setHeight(int height) {
        isMeasured = true;
        if (mAdapter == null && isAdded() && null != mBeanList) {
            mAdapter = new PlaceOrdersBrowseGoodsDetailsRecycleAdapter(mBeanList, height, mActivity);
            mRvContent.setAdapter(mAdapter);
            mAdapter.setOnAddGoodsListener(this);
            mAdapter.setOnItemClickListener(this);
        }
    }

    @Override
    public void ItemClickListener(int position, View view, PlaceOrdersBrowseGoodsBean.ItemListBean dataBean) {
        ((BaseCardDeskActivity) mActivity).hideSearchTitle();
        PlaceOrdersGoodsDeatilsFragment fragment = new PlaceOrdersGoodsDeatilsFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("data", dataBean);
        bundle.putString("demandId", mDemandId);
        bundle.putInt("shppingNum", mShoppingNum);
        fragment.setArguments(bundle);
        pushFragment(fragment);
    }

    @Override
    public void addCLickListener(int position, View view, PlaceOrdersBrowseGoodsBean.ItemListBean dataBean) {
        this.mShoppintView = view;
        Map<String, Object> map = new HashMap<>();
        map.put("contractUkid", dataBean.getContractUkid());
        map.put("demandId", mDemandId);
        map.put("itemPublishUkid", dataBean.getItemPublishUkid());
        map.put("payType", dataBean.getPayType());
        map.put("payTypeValue", dataBean.getPayTypeValue());
        map.put("payWay", dataBean.getPayWay());
        map.put("qty", "1");
        map.put("resourceUkid", dataBean.getResourceUkid());
        map.put("supplierBusinessId", dataBean.getSupplierBusinessId());
        map.put("type", "item");
        loadData(ContractConstant.ADD_SHOPPING_CART, map, ADD_SHOPPINT_CART);
    }

    public void setViewAndViewGroup(View view, ViewGroup viewGroup) {
        this.mConfirmBtn = (Button) view;
        this.mParentItem = (RelativeLayout) viewGroup;
    }

    public void onEventMainThread(PlaceOrdersBrowseConfirmBean bean) {
        if (bean.getType().equals("browseShoppintNum")) {
            mShoppingNum = bean.getShoppingNum();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
